const http = require('http');
const querystring = require('querystring');
const config = require('./config');
const log = require('./log');
const errCode = require('./code');
var isApplfHight = true;  //是否申请高佣
var getP = null; //是否获取了普通和鹊桥佣金比列
var getCommins = {

    getCallbackFunc: null,
    //设置回调
    setCallbackFunc: function (func) {
        this.getCallbackFunc = func;
    },
    //回调设置的函数
    callBackFunc: function (errCode, data) {
        if (!errCode)  return false;
        var func = this.getCallbackFunc;
        if (typeof func === 'function') {
            data = data || {};
            func(errCode, data);
        }
    },
    //函数类型处理
    callFunc: function (func, data, status, option) {
        if (typeof  func === 'function') {
            func(status, data, option);
        }
    },
    //请求事件
    requestHandle: function (response, func, arg) {
        var responseText = [];
        var size = 0;
        var call = this;
        response.on('data', function (data) {
            responseText.push(data);
            size += data.length;
        });
        response.on('end', function () {
            responseText = Buffer.concat(responseText, size);
            try {
                if (!responseText.toString()) {
                    getCommins.callBackFunc(errCode.login);
                    return false;
                }
                var commins = JSON.parse(responseText.toString());
                if (commins.ok) {
                    call.callFunc(func, commins.data, 'yes', arg);
                    return true;
                }
                throw  "error";
            } catch (err) {
                call.callFunc(func, null, 'no', arg);
                log.createLog(err.message, 'Err.log');
                return false;
            }
        });
        response.on('error', function (e) {
        });
    },

    //请求回调
    requestCall: function (cookies, rq, item, type) {
        if (!cookies) return false;
        var p = new Promise((resolve, reject) => {
            rq = rq || {};
            item = item || {};
            type = type || 'GET';
            var conf = this.getHttpConfig(cookies, rq, item, type);
            if (!conf) {
                return false;
            }
            if (type.toUpperCase() !== 'POST') {
                conf.re.path = conf.re.path + '?' + conf.arg;
            }
            var req = http.request(conf.re, function (response) {
                var responseText = [];
                var size = 0;
                response.on('data', function (data) {
                    responseText.push(data);
                    size += data.length;
                });
                response.on('end', function () {
                    responseText = Buffer.concat(responseText, size);
                    try {
                        if (!responseText.toString()) {
                            reject(errCode.login);
                            return false;
                        }
                        var commins = JSON.parse(responseText.toString());
                        if (commins.ok) {
                            resolve(commins.data);
                        } else {
                            throw  "error";
                        }
                    } catch (err) {
                        reject(err);
                        log.createLog(err.message, 'Err.log');
                        return false;
                    }
                });
                response.on('error', function (e) {
                    reject(e);
                });
            });
            if (type.toUpperCase() == 'POST') {
                req.write(conf.arg);
            }
            req.end();
        });
        return p;
    },
    //申请高佣
    applfCommins: function (cookies, campId, keeperid) {
        if (!campId || !keeperid) {
            log.createLog('申请高佣失败，没有campId或keeperid' + campId + '#' + keeperid, 'applfComminsErr.log');
            return false;
        }
        var item = {
            campId: campId,
            keeperid: keeperid,
            applyreason: config.sq_remark
        };
        var host = {
            path: config.sq_path
        };
        return this.requestCall(cookies, host, item, 'POST', applf, null);
    },

    /**
     * 起始地方
     * @param cookies
     * @param url
     * @param ad  推广位
     * @param hight 是否申请高佣
     * @returns {boolean}
     */
    start: function (cookies, url, ad, hight) {
        if (!cookies || !url) {
            return false;
        }
        var id = url.match(/id=(\d+)/);
        if (!id) {
            return false;
        }
        hight = hight || true;
        var itemId =id[1];
        this.searchRate(cookies, url).then(function (data) {
            getPuTong(data, 'yes');
            var func = [];
            var q=[];
            if (hight && itemId && isApplfHight) {
                q.push(this.searchHightCommins(cookies, itemId));
                func.push(getHight);
            }
            if (ad && itemId) {
                var extend={};
                if (isApplfHight) {
                    extend={scenes:3,channel:'tk_qqhd'}; //鹊桥
                } else {
                    extend={scenes:1};//超级搜索
                }
                q.push(this.converAll(cookies, itemId, ad,extend)); // 转换链接
                func.push(convert);
            }
            if (q.length < 1) {
                return false;
            }
            var call = this;
            Promise.all(q).then(function (d) {
                var next=[];
                for (var i = 0; i < d.length; i++) {
                    var temp = func[i](d[i]);
                    if(typeof temp ==='object' && temp.length !=='undefined'){
                        next.push(temp);
                    }
                }
                return next;
            }).then(d=> {
                for(var i=0;i<d.length;i++){
                    if(d[i][0] ==='applf'){
                        call.applfCommins(cookies, d[i][1], d[i][2]);
                    }
                }
            }).catch(e=> {
                console.log(e);
                throw  e;
            });
        }.bind(this)).catch((err)=> {
            if (err == errCode.login) {
                getCommins.callBackFunc(errCode.login);
            }
            console.log(err, 'err');
        });


    },
    //获取定向佣金比列
    searchHightCommins: function (cookies, itemId) {

        if (!cookies || !itemId) {
            return false;
        }
        var item = {
            itemId: itemId
        };
        var arg = {cookie: cookies};

        return this.requestCall(cookies, {path: config.hc_path}, item, 'GET', getHight, arg);
    },
    //获取普通佣金比列:
    searchRate: function (cookie, url) {
        if (!cookie || !url) {
            return false;
        }
        var item = {q: url};
        var op = {path: config.search_path};
        return this.requestCall(cookie, op, item, 'GET');
    },
    //转换工具链接
    convertHttp: function (cookies, url, adzone) {
        if (!url || !adzone || !cookies) {
            return false;
        }
        var site = adzone.split('_');
        var item = {
            siteid: site[2],
            adzoneid: site[3],
            promotionURL: url,
            _input_charset: 'utf-8'
        };
        return this.requestCall(cookies, {path: config.ad_path}, item, 'GET');
    },

    //推广转链接
    converAll:(cookies,itemId,adzone,extend)=>{
        if(!cookies || !itemId || !adzone){
            return false;
        }
        extend = extend || {};
        var site = adzone.split('_');
        var item = {
            siteid: site[2],
            adzoneid: site[3],
            auctionid: itemId,
            _input_charset: 'utf-8'
        };
        item = Object.assign(item,extend);
        return this.requestCall(cookies, {path: config.cov_path}, item, 'GET');
    },
    //请求的参数信息
    getHttpConfig: function (cookies, r_option, arg_option, type) {
        if (!r_option || !cookies) {
            return false;
        }
        type = type || 'POST';
        arg_option = arg_option || {};
        var date = new Date();
        var reqData = querystring.stringify(Object.assign(arg_option, {
            t: date.getTime(),
            _tb_token_: cookies._tb_token_
        }));
        var param = [];
        for (var i in cookies) {
            param.push(i + '=' + cookies[i]);
        }
        var header = {
            'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',
            'Accept': 'application/json, text/javascript, */*; q=0.01',
            'Cookie': param.join('; ')
        };
        if (type.toUpperCase() === 'POST') {
            header['Content-Length'] = Buffer.byteLength(reqData);
        }
        var post_options = Object.assign(r_option, {
            host: config.sq_host,
            port: config.sq_port,
            method: type,
            headers: header
        });
        return {
            arg: reqData,
            re: post_options
        };
    }
};


//获取高佣
function getHight(data, option) {
    var len = data.length;
    var exits = false;
    var campId = keeperid = '';
    var mo = 0;
    //比较最高佣金
    for (var i = 0; i < len; i++) {
        //高佣若已经申请过则不继续申请
        if (data[i].Exist) {
            exits = true;
            break;
        }
        if (data[i].commissionRate > mo) {
            campId = data[i].CampaignID;
            keeperid = data[i].ShopKeeperID;
            mo = data[i].commissionRate;
            break;
        }
    }
    if (!exits && campId && keeperid) {
        return ['applf',campId, keeperid];
    }
    return false;
}

//超级搜索佣金
function getPuTong(data) {
    getP = true;
    if (typeof  data.length == 'undefined') {
        var info = data.pageList;
    } else {
        var info = data[0].pageList;
    }
    var avg = info[0].eventRate;
    var ding = info[0].tkSpecialCampaignIdRateMap;
    var s = 0;
    for (var i in ding) {
        if (ding[i] > s) {
            s = ding[i];
        }
    }
    if (avg >= s) {
        isApplfHight = false;
    }

}

//申请高佣
function applf(data) {
    getCommins.callBackFunc(errCode.applfLoding, {'status': 'yes'});
}


//转高佣链接
function convert(data) {
    getCommins.callBackFunc(errCode.convert, {'status': 'cov'});
    log.convertLog(data.couponLink?data.couponLink:data.sclick);
}

module.exports = getCommins;